import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hm_show_flutter/api/service/home_service.dart';
import 'package:hm_show_flutter/api/service/user_service.dart';
import 'package:hm_show_flutter/entity/company.dart';
import 'package:hm_show_flutter/entity/company_entity.dart';
import 'package:hm_show_flutter/entity/home_entity.dart';
import 'package:hm_show_flutter/entity/version_entity.dart';
import 'package:hm_show_flutter/event/company_event.dart';
import 'package:hm_show_flutter/page/home/swiper_view.dart';
import 'package:hm_show_flutter/constant/string.dart';
import "package:flutter_easyrefresh/easy_refresh.dart";
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hm_show_flutter/style/style.dart';
import 'package:hm_show_flutter/utils/http_util.dart';
import 'package:hm_show_flutter/utils/navigator_util.dart';
import 'package:flutter_easyrefresh/bezier_bounce_footer.dart';
import 'package:hm_show_flutter/utils/permission_util.dart';
import 'package:hm_show_flutter/utils/toast_util.dart';
import 'package:hm_show_flutter/utils/version_upgrade.dart';
import 'package:hm_show_flutter/widgets/AppLoadingDialog.dart';
import 'package:hm_show_flutter/widgets/menu_view.dart';
import 'package:hm_show_flutter/widgets/loading_dialog.dart';
import 'package:flutter_easyrefresh/bezier_circle_header.dart';
import 'package:hm_show_flutter/utils/shared_preferences_util.dart';
import 'package:hm_show_flutter/widgets/popular_view.dart';
import 'package:hm_show_flutter/widgets/recommend_view.dart';
import 'package:hm_show_flutter/widgets/search_view.dart';
import 'package:package_info/package_info.dart';
import 'package:r_upgrade/r_upgrade.dart';

///首页
class HomeView extends StatefulWidget {
  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {
  HomeService _homeService = new HomeService();
  HomeEntity _homeEntity;
  EasyRefreshController _controller = EasyRefreshController();

  List<CompanyModel> _listCompany;
  String _companyName;
  int _companyId;

  @override
  void initState() {
    super.initState();
    _getHomeData();
    //获取登录时保存的门店数据
    SharedPreferencesUtils.getCompany().then((model) {
      if (model != null) {
        setState(() {
          _companyId = model.id;
          _companyName = model.name;
        });
      } else {}
    });
    checkAppUpdate();
  }

  double _appbarHeight = ScreenUtil.instance.height * 0.036;

  _getHomeData() {
    //获取首页数据
    _homeService.getHomeData((success) {
      setState(() {
        _homeEntity = success;
      });
      _controller.finishRefresh();
    }, (fail) {
      ToastUtil.showToast(fail);
      _controller.finishRefresh();
    });

    //获取门店列表
    _homeService.getCompanyListData((success) {
      setState(() {
        CompanyEntity entity = success;
        setState(() {
          _listCompany = entity.data.companyList;
        });
      });
    }, (fail) {});
  }

  @override
  Widget build(BuildContext context) {
    Widget _titleHome() {
      return ConstrainedBox(
          constraints: BoxConstraints(maxHeight: 35),
          child: Row(
            children: <Widget>[
              Container(
                width: 60,
                padding: EdgeInsets.only(right: 3),
                child: Text(
                  _companyName == null ? " " : _companyName,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Colors.white, fontSize: 12),
                ),
              ),
              Expanded(
                  child: TextField(
                      autofocus: false,
                      onTap: () {
                        FocusScope.of(context).requestFocus(new FocusNode());
                        NavigatorUtils.goSearchGoods(context);
                      },
                      scrollPadding: EdgeInsets.only(left: 0),
                      decoration: InputDecoration(
                        contentPadding:
                            const EdgeInsets.symmetric(vertical: 2.0),
                        hintText: '请输入搜索内容',
                        hintStyle: TextStyle(fontSize: 14),
                        prefixIcon: Icon(
                          Icons.search,
                          color: AppColors.mainColor,
                        ),
                        border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(32),
                            borderSide: BorderSide.none),
                        filled: true,
                        fillColor: Colors.white,
                      )))
            ],
          ));
    }

    Widget _moreStore() {
      return PopupMenuButton(
        offset: Offset(0, _appbarHeight * 2 + 15),
        child: Container(
          padding: EdgeInsets.only(right: 8),
          child: Icon(
            Icons.more_vert,
            color: Colors.white,
          ),
        ),
        itemBuilder: (BuildContext context) {
          if (_listCompany == null) {
            return <PopupMenuItem<String>>[];
          } else {
            List<PopupMenuEntry> list = List<PopupMenuEntry>();
            for (CompanyModel company in _listCompany) {
              list.add(PopupMenuItem(
                child: Text(
                  company.name,
                  style: TextStyle(
                      fontSize: 13,
                      color:
                          company.id == _companyId ? Colors.red : Colors.black),
                ),
                height: 35,
                value: company.id,
              ));
            }
            return list;
          }
        },
        onSelected: (value) {
          for (CompanyModel company in _listCompany) {
            if (company.id == value) {
              setState(() {
                if (_companyId != company.id) {
                  //切换门店
                  _companyName = company.name;
                  _companyId = company.id;
                  SharedPreferencesUtils.saveCompany(
                      CompanyModel(name: _companyName, id: _companyId));
                  _getHomeData();
                  companyEventBus
                      .fire(CompanyEvent(name: _companyName, id: _companyId));
                }
              });
              return;
            }
          }
        },
      );
    }

    Widget contentWidget() {
      return _homeEntity == null
          ? LoadingDialog()
          : Container(
              child: EasyRefresh(
                controller: _controller,
                header:
                    BezierCircleHeader(backgroundColor: AppColors.mainColor),
                footer:
                    BezierBounceFooter(backgroundColor: AppColors.mainColor),
                enableControlFinishRefresh: true,
                enableControlFinishLoad: false,
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      SwiperView(_homeEntity.data.carouselList,
                          ScreenUtil.instance.setHeight(400.0)),
                      Padding(
                        padding: EdgeInsets.only(top: 15.0),
                      ),
                      HomeMenuView(_homeEntity.data.appMenuList),
                      RecommendView(_homeEntity.data.recommendList),
                      PopularView(_homeEntity.data.popularList)
                    ],
                  ),
                ),
                onRefresh: () async {
                  _getHomeData();
                },
              ),
            );
    }

    return Scaffold(
      appBar: PreferredSize(
          child: AppBar(
            automaticallyImplyLeading: false,
            titleSpacing: 8,
            title: _titleHome(),
            actions: <Widget>[_moreStore()],
          ),
          preferredSize: Size.fromHeight(_appbarHeight)),
      body: contentWidget(),
    );
  }

  void checkAppUpdate() async {
    UserService _userService = new UserService();

    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    int _versionCode = int.parse(packageInfo.buildNumber);

    _userService.getAppVersion((success) {
      VersionEntity entity = success;
      VersionData _versionInfo = entity.data;
      print("当前versionCode：" +
          _versionCode.toString() +
          " 最新versionCode：" +
          _versionInfo.versionCode.toString());
      if (_versionCode < _versionInfo.versionCode) {
        if (Platform.isIOS) {
          ToastUtil.showToast("请前往App store更新应用");
          return;
        }
        showDialog<bool>(
            context: context,
            builder: (BuildContext context) {
              return WillPopScope(
                onWillPop: () async => !_versionInfo.force,
                child: _buildDialog(context, _versionInfo),
              );
            },
            barrierDismissible: false);
      }
    }, onFail: (fail) {});
  }

  Widget _buildDialog(
    BuildContext context,
    VersionData versionData,
  ) {
    List<Widget> _buttons = <Widget>[];

    if (versionData.force) {
      _buttons.add(_buttonUpdate(versionData.name,versionData.url));
    } else {
      _buttons.add(_buttonNext());
      _buttons.add(_buttonUpdate(versionData.name,versionData.url));
    }

    return CupertinoAlertDialog(
      title: Text('立即更新${versionData.name}?', style: TextStyle(fontSize: 14)),
      content: Column(
        children: <Widget>[
          Padding(padding: EdgeInsets.only(top: 10)),
          Text('检测到新版本 ${versionData.versionName}',
              style: TextStyle(fontSize: 12)),
          Padding(padding: EdgeInsets.only(top: 6)),
          Text(versionData.description, style: TextStyle(fontSize: 12)),
        ],
      ),
      actions: _buttons,
    );
  }

  Widget _buttonUpdate(String name,String url) {
    return CupertinoDialogAction(
      child: const Text('立即更新', style: TextStyle(fontSize: 13)),
      onPressed: () {
        Navigator.pop(context, true);
        PermissionUtil.checkStoragePermission().then((isGranted) {
          if (isGranted) {
            //有权限
            updateApp(name, url);
          }
        });

//        VersionUpgrade upgrade = new VersionUpgrade();
//        upgrade.executeDownload(name, url);

      },
    );
  }

  void updateApp(String name,String url) async{
    int  id = await RUpgrade.upgrade(
        url,
        apkName: name,
        isAutoRequestInstall: true);
  }


  Widget _buttonNext() {
    return CupertinoDialogAction(
      child: const Text('下次再说',
          style: TextStyle(fontSize: 13, color: Colors.grey)),
      onPressed: () {
        Navigator.pop(context, true);
      },
    );
  }
}
